package com.dz;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dz.pojo.Crime;
import com.dz.pojo.CrimeLab;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.security.auth.callback.Callback;

public class CrimeListFragment extends Fragment {

    private RecyclerView mRecyclerView;
    private CrimeAdapter mCrimeAdapter;
    private int clickCrimeId;
    private TextView mNoCrimeText;
    private Button mAddCrime;
    //记录子标题变量
    private boolean mSubtitleVisible;
    //解决设备旋转问题时的变量值
    private static final String SAVED_SUBTITLE_VISIBLE = "subtitle";
    //
    private Callbacks mCallbacks;

    public interface Callbacks{
        void onCrimeSelected(Crime crime);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mCallbacks= (Callbacks) context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (savedInstanceState!=null){
            mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE);
        }
        View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
        mRecyclerView = view.findViewById(R.id.crime_recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mNoCrimeText = view.findViewById(R.id.no_crime_text);
        mAddCrime = view.findViewById(R.id.add_crime);
        updateUI();
        return view;
    }
    //要保证fragment视图得到刷新，在onResume方法中更新代码是最安全的选择
    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }


    public  void updateUI() {
        CrimeLab crimeLab=CrimeLab.get(getActivity());
        List<Crime> crimes = crimeLab.getCrimes();
        if (mCrimeAdapter==null){
            mCrimeAdapter = new CrimeAdapter(crimes);
            mRecyclerView.setAdapter(mCrimeAdapter);
        }
        else{
            //局部刷新
//            mCrimeAdapter.notifyItemChanged(clickCrimeId);
            mCrimeAdapter.setCrimes(crimes);
            //全局刷新
            mCrimeAdapter.notifyDataSetChanged();
        }
        if (crimes.size()==0){
            mNoCrimeText.setVisibility(View.VISIBLE);
            mAddCrime.setVisibility(View.VISIBLE);
            mAddCrime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Crime crime = new Crime();
                    CrimeLab.get(getActivity()).add(crime);
                    Intent intent = CrimePageActivity.newIntent(getActivity(), crime.getId());
                    startActivity(intent);
                }
            });
        }
        else {
            mNoCrimeText.setVisibility(View.INVISIBLE);
            mAddCrime.setVisibility(View.INVISIBLE);
        }
        updateSubtitle();
    }

    //ViewHolder 内部类
    private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        private TextView mTitleTextView;
        private TextView mDateTextView;
        private Crime mCrime;
        private ImageView mSolvedImageView;
        public CrimeHolder(LayoutInflater inflater,ViewGroup parent) {
            super(inflater.inflate(R.layout.list_item_crime,parent,false));
            itemView.setOnClickListener(this);
            mTitleTextView= itemView.findViewById(R.id.crime_title);
            mDateTextView = itemView.findViewById(R.id.crime_date);
            mSolvedImageView=itemView.findViewById(R.id.crime_solved);
        }
        public void bind(Crime crime){
            mCrime=crime;
            mTitleTextView.setText(mCrime.getTitle());
            //将日期格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(mCrime.getDate());
            mDateTextView.setText(format);
            mSolvedImageView.setVisibility(crime.isSolved()?View.VISIBLE:View.GONE);
        }
        @Override
        public void onClick(View view) {
//            Toast.makeText(getActivity(),mCrime.getTitle()+" clicked",Toast.LENGTH_SHORT).show();
//            Intent intent = new Intent(getActivity(), MainActivity.class);
            CrimeLab crimeLab = CrimeLab.get(getActivity());
//            clickCrimeId = crimeLab.getCrimeIndex(mCrime);

//            Intent intent = CrimePageActivity.newIntent(getActivity(), mCrime.getId());
//
//            Log.d("crimeId_1",mCrime.getId()+"");
//            startActivity(intent);
            mCallbacks.onCrimeSelected(mCrime);
        }
    }
    private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder>{

        private List<Crime> mCrimes;

        public CrimeAdapter(List<Crime> crimes){
            mCrimes=crimes;
        }

        @NonNull
        @Override
        public CrimeHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            return new CrimeHolder(layoutInflater,parent);
        }

        @Override
        public void onBindViewHolder(@NonNull CrimeHolder holder, int position) {
            Crime crime = mCrimes.get(position);
            holder.bind(crime);
        }

        @Override
        public int getItemCount() {
            return mCrimes.size();
        }
        public void setCrimes(List<Crime> crimes){
            mCrimes = crimes;
        }
    }
   //实例化选项菜单
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_crime_list,menu);
        MenuItem item = menu.findItem(R.id.show_subtitle);
        if (mSubtitleVisible){
            item.setTitle(R.string.hide_subtitle);
        }
        else
            item.setTitle(R.string.show_subtitle);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //让FragmentManger知道CrimeListFragment需接收选项菜单方法回调
        setHasOptionsMenu(true);
    }
    //响应菜单项选择事件

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.new_crime:
                Crime crime = new Crime();
                CrimeLab.get(getActivity()).add(crime);
//                Intent intent = CrimePageActivity.newIntent(getActivity(), crime.getId());
//                startActivity(intent);
                updateUI();
                mCallbacks.onCrimeSelected(crime);
                return true;
            case R.id.show_subtitle:
                //点击的时候更新菜单项
                mSubtitleVisible=!mSubtitleVisible;
                getActivity().invalidateOptionsMenu();
                updateSubtitle();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    //设置工具栏子标题
    private void updateSubtitle(){
        CrimeLab crimeLab = CrimeLab.get(getActivity());
        int crimeCount = crimeLab.getCrimes().size();
        //使用了占位符，用crimeCount来代替占位符
        String subtitle = getResources().getQuantityString(R.plurals.subtitle_plural, crimeCount, crimeCount);
//        String subtitle = getString(R.string.subtitle_format, crimeCount);
        if (!mSubtitleVisible){
            subtitle = null;
        }
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.getSupportActionBar().setSubtitle(subtitle);
    }

    //解决设备旋转问题，subtitle重置
    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(SAVED_SUBTITLE_VISIBLE,mSubtitleVisible);
    }
}
